<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="addInOrOut"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="showAdd"
      @close="closeShow"
      width="55%"
    >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
            <el-row :gutter="0">    
            <el-col :span="6">
                <el-form-item label="认证类别" prop="certificationCategory"  label-width="80px" >
                    <el-select 
                         v-model="createForm.certificationCategory" 
                         clearable      
                         filterable
                         placeholder="请选择类别"
                         class="ul-item">
                         <el-option :value="item" :label="item" v-for="(item,index) in this.typeList" :key="index"/>
                    </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="姓名" prop="userName"  label-width="80px" >
                  <el-select filterable clearable v-model="createForm.userName" placeholder="请选择姓名" @focus="focusName" class="ul-item">
                    <el-option :value="item.userName" :label="item.userName" v-for="(item,index) of this.nameList" :key="index"/>
                  </el-select>
                  <!-- <el-input placeholder="请输入姓名" clearable v-model.trim="createForm.userName" class="ul-item"/> -->
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="所在部门" prop="workCenter" label-width="80px" >
                <el-select
                    v-model="createForm.workCenter"
                    @focus="getCenterList" 
                    placeholder="请选择部门"
                    class="ul-item"
                    filterable
                    clearable>
                    <el-option
                        v-for="(item,index) in this.centerList"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所在岗位" prop="jobTitle"  label-width="80px">
                <el-select
                    v-model="createForm.jobTitle"
                    placeholder="请选择所在岗位"
                    filterable
                    clearable   
                    class="ul-item">
                    <el-option
                        v-for="(item,index) in this.postList"
                        :key="index"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
              </el-form-item>
            </el-col>
           </el-row>
           <el-row :gutter="0">    
            <el-col :span="6">
              <el-form-item label="资质类型" prop="typeOfQualification"  label-width="80px" >
                <el-select 
                     v-model="createForm.typeOfQualification" 
                     clearable      
                     filterable
                     placeholder="请选择资质类型"
                     class="ul-item">
                     <el-option :value="item" :label="item" v-for="(item,index) in this.certificationLs" :key="index"/>
                </el-select>
                <!-- <el-input placeholder="请输入姓名" clearable v-model.trim="createForm.userName" class="ul-item"/> -->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="认证时间" prop="attestationTime" label-width="80px" >    
                <el-date-picker
                        v-model="createForm.attestationTime"
                        type="datetime"
                        placeholder="选择考核时间"
                        align="right"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"  
                        style="width: 180px"
                        >
                    </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训内容" label-width="80px" prop="trainableContentCategories">
                <div v-for="(items,index1) in trainableList" :key="index1" style="margin-bottom: 5px;">
                  <el-cascader :options="contentList" filterable @change="contentChang($event,index1)" @focus="getContent" v-model="items.name" placeholder="请选择" style="width:250px">
                    <!-- <el-option
                    v-for="(item,index) in contentList"
                    :key="index"
                    :label="item.trainingContent"
                    :value="item.trainingContent">
                  </el-option> -->
                </el-cascader>
                <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delPost(index1)"></el-button>
                <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addPost"></el-button>
              </div>
            </el-form-item>
              <!-- <el-form-item label="培训内容" prop="trainableContentCategories" label-width="80px" >
                <el-input placeholder="请输入培训内容" clearable v-model.trim="createForm.trainableContentCategories" class="ul-item"/>  
              </el-form-item> -->
            </el-col>
           </el-row>
           <el-form-item label="认证人员" prop="certifyingOfficer"  label-width="80px" >
            <el-select filterable clearable v-model="createForm.certifyingOfficer" placeholder="请选择认证人员" @focus="focusName" style="width: 155px;">
              <el-option :value="item.userName" :label="item.userName" v-for="(item,index) of this.nameList" :key="index"/>
            </el-select>
            </el-form-item>
            <el-form-item label="认证记录" prop="certificationRecord"  label-width="120px" >
                <el-upload
                  class="upload-demo"
                  action="http://192.168.3.11:8086/technologyFile"
                  :on-success="handlePdfSuccess"
                  :on-remove = "removePdf"  
                  :on-change= "pdfRemove"
                  :headers="getHttpHeader"
                  :before-upload="beforeFilsUpload"
                  :limit="1"
                  :file-list="fileList">
                  <el-button :disabled="bool1" size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            :loading="loadBool"
            >确 认</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
      <el-select 
             v-model="param.certificationCategory" 
             clearable      
             filterable
             style="margin-right: 15px;width: 140px"
             placeholder="请选择类别"
             class="ul-item">
             <el-option :value="item" :label="item" v-for="(item,index) in this.typeList" :key="index"/>
        </el-select>

        <el-select filterable clearable v-model="param.userName" placeholder="请选择姓名" @focus="getTutor" style="margin-right: 15px;width: 150px">
          <el-option :value="item.userName" :label="item.userName" v-for="(item,index) of this.tutorList" :key="index"/>
        </el-select>

        <el-select 
             v-model="param.workCenter" 
             clearable      
             filterable
             style="margin-right: 15px;width: 140px"
             @focus="getCenterList" 
             placeholder="请选择部门"
             class="ul-item">
             <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
        </el-select>

        <el-select 
             v-model="param.typeOfQualification" 
             clearable      
             filterable
             style="margin-right: 15px;width: 140px"
             placeholder="请选择资质类型"
             class="ul-item">
             <el-option :value="item" :label="item" v-for="(item,index) in this.certificationLs" :key="index"/>
        </el-select>

        <el-select 
         @focus="getContent1"
             v-model="param.trainableContentCategories" 
             clearable      
             filterable
             style="margin-right: 15px;width: 180px"
             placeholder="请选择培训内容"
             class="ul-item">
             <el-option :value="item.trainingContent" :label="item.trainingContent" v-for="(item,index) in this.contentList" :key="index"/>
        </el-select>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="认证类别"  prop="certificationCategory" align="center"/>
      <el-table-column label="姓名"  prop="userName" align="center"/>
      <el-table-column label="所在部门"  prop="workCenter" align="center"/>
      <el-table-column label="所在岗位"  prop="jobTitle" align="center"/>
      <el-table-column label="资质类型"  prop="typeOfQualification" align="center"/>
      <el-table-column label="认证时间"  prop="attestationTime" align="center"/>
      <el-table-column label="可培训内容"  prop="trainableContentCategories" align="center" width="200px"/>
      <el-table-column label="认证人员"  prop="certifyingOfficer" align="center"/>
      <el-table-column label="认证记录"  prop="certificationRecord" align="center" width="200px">
        <template slot-scope="scope" >  
          <el-link style="font-size: 12px" :href="scope.row.certificationRecord" target="_blank">{{scope.row.certificationRecord}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="累计培训课次"  prop="cumulativeTrainingSessions" align="center"/>
      <el-table-column label="累计培训时长"  prop="cumulativeTrainingDuration" align="center"/>
      <el-table-column label="评价分"  prop="evaluationScore" align="center"/>
      <el-table-column label="修改人员"  prop="updateJobNumber" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/>
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { tutorFind,tutorSave,tutorUpd,tutorDel,programFind } from "@/api/knowledgeSkill"
import { findUserListGroup } from '@/api/chargingData.js'
import { getCenter } from '../../api/workSection.js'
import mixin from '../../utils/mixin.js'    
export default {
    name: 'mentorManagement',
    mixins: [mixin],
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                code: '',                      
                content: ''                    
            },
            title: '新增',
            total: 0,                                      //数据的总数
            tableInfo: [],
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            nameList:[],
            props: { multiple: true },
            loadBool:false,
            // 表单校验
            addRules: {
                certificationCategory: [
                    { required: true, message: "认证类别不能为空!", trigger: "change" },
                ],
                userName: [
                    { required: true, message: "姓名不能为空!", trigger: "change" },
                ],
                workCenter: [
                    { required: true, message: "所在部门不能为空!", trigger: "change" },
                ],
                jobTitle: [
                    { required: true, message: "所在岗位不能为空!", trigger: "change" },
                ],
                typeOfQualification: [
                    { required: true, message: "资质类型不能为空!", trigger: "change" },
                ],
                attestationTime: [
                    { required: true, message: "认证时间不能为空!", trigger: "change" },
                ],
                // trainableContentCategories: [
                //     { required: true, message: "培训内容不能为空!", trigger: "change" },
                // ],
                certifyingOfficer: [
                    { required: true, message: "认证人员不能为空!", trigger: "change" },
                ],
                certificationRecord: [
                    { required: true, message: "认证记录不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            certificationLs:['初级','中级','高级','专家'],
            typeList:['讲师','导师'],
            postList:['1线','1.5线','2线'],
            fileList:[], 
            bool1: false,
            getHttpHeader: {                    //上传文件的头
                Authorization: '',              //传输文件的token
                CHECK_USER_VALUE: 'GOLWAY',
                CHECK_PASSWORD_VALUE: '8D4DD3F80CEB6149329FDBD590B164F1'
            },
            contentList:[],
            trainableList:[{name:''}],
            tutorList:[]    // 导师列表
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
      // 获取导师列表
      async getTutor(){
            let query = {page:1,limit:10000}
            const {data} = await tutorFind(query)
            // 姓名去重 
            const seenIds = new Set();
            const uniqueArray = data.list.filter(item => {
                if (!seenIds.has(item.userName)) {
                    seenIds.add(item.userName);
                    return true;
                }
                return false;
            });
            this.tutorList = uniqueArray
        },
      async focusName(){
            let query = {page:1,limit:9999,status: 1}
            const {data} = await findUserListGroup(query)
            console.log(data)
            this.nameList = data
        },
        // 删除培训内容
        delPost(index){
        if(this.trainableList.length == 1){
          this.trainableList = [{name:''}]
        } else {
          this.trainableList.splice(index, 1);
        }
      },
      // 添加培训内容
      addPost(){
        this.trainableList.push({name:''})
      },
        // 获取培训内容
        async getContent(){
        const {data} = await programFind({page:1,limit:9999})
        this.contentList = data.list
        const map = data.list.map(item => item.contentType)
        const uniqueArray = [...new Set(map)]; 
        this.contentList = uniqueArray.map(item =>({
          value: item,
          label: item,
          children: data.list.filter(elm => elm.contentType == item).map(e => ({value:e.trainingContent,label:e.trainingContent}))
        }))
        },
        // 获取培训内容1
        async getContent1(){
        const {data} = await programFind({page:1,limit:9999})
        this.contentList = data.list
        },
        // 修改培训内容
        contentChang(e,index1){
            if(e){
            delete this.trainableList[index1].name
            this.trainableList[index1].name = e[1]
          }
        },
        // 文件上传之前的函数，将token传入头中
        beforeFilsUpload(file) {
            this.getHttpHeader.Authorization = this.dealCookie()
        },
        // cookies的处理函数
        dealCookie() {
            const strcookie = document.cookie                     //获取cookie字符串
            const arrcookie = strcookie.split("; ")               //分割
            for ( var i = 0; i < arrcookie.length; i++) {
                const arr = arrcookie[i].split("=")
                if (arr[0] == "agent_Authorization") {
                    return arr[1]
                }
            }
            return ""
        },
        pdfRemove(e){
            if(e.status == 'fail') return this.$message.error("文件上传失败!")
            else if(e.status == 'success') return this.$message.success("文件上传成功!")
        },
        // 移除pdf
        async removePdf(file) {
          this.bool1 = false
          return this.createForm.certificationRecord = ''
        },
         // 上传PDF文档成功回调函数
         handlePdfSuccess(response) {
          this.bool1 = true
          this.createForm.certificationRecord = response.results
          console.log(1,this.createForm.certificationRecord)
        },
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.certificationCategory){ query.certificationCategory = this.param.certificationCategory}
            if(this.param.userName){ query.userName = this.param.userName}
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
            if(this.param.typeOfQualification){ query.typeOfQualification = this.param.typeOfQualification}
            if(this.param.trainableContentCategories){ query.trainableContentCategories = this.param.trainableContentCategories}
            let data = await tutorFind(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            certificationCategory: '认证类别',
            userName: '姓名',
            workCenter: '所在部门',
            jobTitle: '所在岗位',
            typeOfQualification: '资质类型',
            attestationTime: '认证时间',
            trainableContentCategories: '可培训内容类别',
            certifyingOfficer: '认证人员',
            certificationRecord: '认证记录',
            cumulativeTrainingSessions: '累计培训课次',
            cumulativeTrainingDuration: '累计培训时长',
            evaluationScore: '评价分',
            updateJobNumber: '修改人员',
            updateTime: '修改时间',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await tutorDel({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1
          query.limit = 10000
          if(this.param.certificationCategory){ query.certificationCategory = this.param.certificationCategory}
          if(this.param.userName){ query.userName = this.param.userName}
          if(this.param.workCenter){ query.workCenter = this.param.workCenter}
          if(this.param.typeOfQualification){ query.typeOfQualification = this.param.typeOfQualification}
          if(this.param.trainableContentCategories){ query.trainableContentCategories = this.param.trainableContentCategories}
          let arr = await tutorFind(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '讲师&导师管理', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              certificationCategory:item.certificationCategory,
              userName:item.userName,
              workCenter:item.workCenter,
              jobTitle:item.jobTitle,
              typeOfQualification:item.typeOfQualification,
              attestationTime:item.attestationTime,
              trainableContentCategories:item.trainableContentCategories,
              certifyingOfficer:item.certifyingOfficer,
              certificationRecord:item.certificationRecord,
              cumulativeTrainingSessions:item.cumulativeTrainingSessions,
              cumulativeTrainingDuration:item.cumulativeTrainingDuration,
              evaluationScore:item.evaluationScore,
              updateJobNumber:item.updateJobNumber,
              updateTime:item.updateTime,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {    
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            console.log(this.createForm)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        closeShow(){
            if(this.title == '修改'){       
                this.createForm = {}
                this.fileList = []
                this.trainableList = [{name:''}]
                this.bool1 = false
                this.$refs.createForm.resetFields()
            }
            this.showAdd = false
        },
        async submitprocess(){
          for (const item of this.trainableList) {  
            console.log(item)
            if(!item.name) return this.$message.error('培训内容不能为空！')
          }
            if(!this.trainableList[this.trainableList.length-1].name) return this.$message.error('培训内容最后一个不能为空！')
            let query = Object.assign({},this.createForm)
            let arr1 = []
            this.trainableList.forEach(item => {
                arr1.push(item.name)
            })
            query.trainableContentCategories = arr1.join(',')
            let data 
            this.loadBool = true
            if(this.title == '新增'){
                data = await tutorSave(query)
            } else {
                data = await tutorUpd(query)
            } 
            const errMsg = data.msg
            this.loadBool = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
            this.createForm = {}
            this.fileList = []
            this.trainableList = [{name:''}]
            this.bool1 = false
            this.$refs.createForm.resetFields()
        },
        handleEdit(row){
            this.title = '修改'
            this.createForm = Object.assign({},row) 
            // let arr = []
            // this.trainableList[0].name = this.createForm.trainableContentCategories
            this.$set(this.trainableList[0],'name',row.trainableContentCategories)
            this.$set(this.trainableList[0],'name',row.trainableContentCategories)
            // if(this.createForm.trainableContentCategories){
            //     arr = this.createForm.trainableContentCategories.split(',')
            //     this.trainableList = arr.map((item,index) => ({
            //       name: item,
            //     }))
            // }
            if(row.certificationRecord){
                this.fileList = [{name: 'food.jpeg', url: row.certificationRecord}]
                this.bool1 = true
            }
            this.showAdd = true
        },
        addInOrOut(){
            this.title = '新增'
            this.showAdd = true
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
